<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input :placeholder="$t('请输入搜索关键字')" v-model="listQuery.keyword" style="width: 200px;" class="filter-item"
                @keyup.enter.native="handleFilter"/>
      <el-select v-model="listQuery.status" :placeholder="$t('请选择状态')" clearable class="filter-item"
                 style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name"
                   :value="item.key"/>
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{
        $t('table.search') }}
      </el-button>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="ResetSearch">{{
        $t('重置') }}
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange">
      <el-table-column label="动态id" prop="dynamic_id" sortable="custom" align="center" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.dynamic_id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" prop="title" sortable="custom" align="center" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="展示图片"
        label="展示图片"
        sortable
        width="180">
        <template slot-scope="scope">
          <img :src="scope.row.show_image" alt="" style="width: 50px;height: 50px">
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="create_time" sortable="custom" align="center"
                       width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.create_time | formatDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" prop="status" sortable="custom" align="center"
                       width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.status==0?'待审核':(scope.row.status==2?'审核通过':'审核拒绝') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="success"
            @click.native.prevent="showArticle(scope.row)">预览
          </el-button>
          <el-button
            size="mini" v-show="scope.row.status==0"
            @click.native.prevent="showExamineRefuse(scope.row)">审核拒绝
          </el-button>
          <el-button
            size="mini" v-show="scope.row.status==0"
            type="success"
            @click.native.prevent="examinePass(scope.row)">审核通过
          </el-button>
        </template>
      </el-table-column>
      >
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"/>
    <el-dialog
      title="审核拒绝原因"
      :visible.sync="dialogVisible"
      width="40%"
      :before-close="handleClose">
      <el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="60px" class="demo-dynamic">
        <el-form-item
          v-for="(domain, index) in dynamicValidateForm.domains"
          :label="'问题' + (index+1)"
          :key="domain.key"
          :prop="'domains.' + index + '.value'"
          :rules="{required: true, message: '拒绝原因不能为空', trigger: 'blur'}">
          <el-input v-model="domain.value"></el-input>
          <el-button @click.prevent="removeDomain(domain)">删除</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="addDomain">新增拒绝原因</el-button>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
 <el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="examineRefuse">确 定</el-button>
</span>
    </el-dialog>
    <el-dialog
      title="预览"
      :visible.sync="articleVisible"
      width="40%"
      :before-close="handleClose">
      <div>
        <div>{{ShowdynamicInfo.title}}</div>
        <div>作者:{{ShowdynamicInfo.author}}</div>
        <div v-html="ShowdynamicInfo.content"></div>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="articleVisible = false">取 消</el-button>
    <el-button type="primary" @click="articleVisible = false">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
  import {fetchPv, createArticle, updateArticle} from '@/api/article'
  import {fetchList, ExamineDynamic, getOneDynamicInfo} from '@/api/dynamic'
  import waves from '@/directive/waves' // Waves directive
  import {formatDate} from '@/utils'
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

  const calendarTypeOptions = [
    {key: '0', display_name: '待审核'},
    {key: '2', display_name: '审核通过'},
    {key: '4', display_name: '审核拒绝'},
  ]

  // arr to obj ,such as { CN : "China", US : "USA" }
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})

  export default {
    name: 'ComplexTable',
    components: {Pagination},
    directives: {waves},
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      },
      formatDate(time) {
        console.log('shijian')
        console.log(time)
        var date = new Date(time*1000);
        return formatDate(date, 'yyyy-MM-dd');
      }
    },
    data() {
      return {
        error_message: '',
        Examinedynamic_id: '',
        dynamicValidateForm: {
          domains: [{
            value: ''
          }],
        },
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 10,
          importance: undefined,
          keyword: undefined,
          status: undefined,
          sort: '+id'
        },
        importanceOptions: [1, 2, 3],
        calendarTypeOptions,
        showReviewer: false,
        temp: {
          id: undefined,
          importance: 1,
          remark: '',
          timestamp: new Date(),
          title: '',
          type: '',
          status: 'published'
        },
        rules: {
          type: [{required: true, message: 'type is required', trigger: 'change'}],
          timestamp: [{type: 'date', required: true, message: 'timestamp is required', trigger: 'change'}],
          title: [{required: true, message: 'title is required', trigger: 'blur'}]
        },
        downloadLoading: false,
        dialogVisible: false,
        articleVisible: false,
        Showdynamic_id: null,
        ShowdynamicInfo: {
          author: '',
          title: '',
          content: '',
        }
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        this.listLoading = true
        console.log('=====')
        console.log(this.listQuery)
        fetchList({
          page: this.listQuery.page,
          status: this.listQuery.status,
          keyword: this.listQuery.keyword,
          limit: this.listQuery.limit,
        }).then(response => {
          this.list = response.data.data.data
          this.total = response.data.data.total
          setTimeout(() => {
            this.listLoading = false
          }, 1.0 * 1000)
        })
      },
      showArticle(row) {
        this.articleVisible = true
        this.Showdynamic_id = row.dynamic_id
        getOneDynamicInfo({
          dynamic_id: this.Showdynamic_id,
        }).then(response => {
          if (response.status == 200) {
            this.ShowdynamicInfo = response.data.data
          }
        })
      },
      ResetSearch() {
        this.listQuery.status = undefined
        this.listQuery.keyword = undefined
        this.getList()
      },
      showExamineRefuse(row) {
        this.dialogVisible = true
        this.Examinedynamic_id = row.dynamic_id
      },
      examineRefuse() {
        if (this.dynamicValidateForm.domains.length < 1 || this.dynamicValidateForm.domains[0].value.length < 1) {
          this.$notify.error({
            title: '错误',
            message: '审核拒绝信息不能为空!'
          });
        } else {
          ExamineDynamic({
            dynamic_id: this.Examinedynamic_id,
            status: 4,
            error_message: this.dynamicValidateForm.domains
          }).then(response => {
            if (response.status == 200) {
              this.dialogVisible = false
              this.getList()
            }
            setTimeout(() => {
              this.listLoading = false
            }, 1.5 * 1000)
          })
        }
      },
      examinePass(row) {
        ExamineDynamic({dynamic_id: row.dynamic_id, status: 2}).then(response => {
          if (response.status == 200) {
            this.getList()
          }
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
        console.log(row.dynamic_id)
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleModifyStatus(row, status) {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        row.status = status
      },
      sortChange(data) {
        const {prop, order} = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },
      handleClose(done) {
        this.dialogVisible = false
        this.articleVisible = false
      },
      addDomain() {
        this.dynamicValidateForm.domains.push({
          value: '',
          key: Date.now()
        });
      },
      removeDomain(item) {
        var index = this.dynamicValidateForm.domains.indexOf(item)
        if (index !== -1) {
          this.dynamicValidateForm.domains.splice(index, 1)
        }
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            alert('submit!');
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      }
    }
  }
</script>
